Import files from outside the project

2019-07-29 12:05发布

问题:

I'm writing two projects, both in js. Webpack and babel are used. I want to create folder common which will contain files, that are used in each project. For example some constants etc.

So I have such a structure:

|- project
    |- server
        |- config
           |- webpack.config.js
        |- package.json
        |- .babelrc
        |- ...
    |- client
        |- config
           |- webpack.config.js
        |- package.json
        |- .babelrc
        |- index.js
        |- ...
    |- common
        |- constants
            |- http-codes.js

But, it appeared that it's impossible to import files outside the project. eg. it's impossible to do such an import in client/index.js: import * from '../common/constants/http-codes.js'

Do you have any ideas how such an imports could be done?


Update:

files:

common/constants/http-codes.js:

export const SUCCESS = 200;
...

client/index.js:

import { SUCCESS } from 'common/constants/http-codes.js';
...
console.log(SUCCESS);

client/config/webpack.config.js:

...
const PATHS = {
    app: path.resolve(__dirname, '../'),
    build: path.resolve(__dirname, '../build'),
    common: path.resolve(__dirname, '../../common')
};
...
module.exports = {
    resolve: {
        extensions: [ '', '.js', '.jsx', '.styl' ],
        alias: {
            ...,
            common: PATHS.common
        }
    },
    ...
}

回答1:

Did you try using path module from nodejs?